# coding=utf-8
import json

from django.http import HttpResponse
from django.shortcuts import render

from dockerManagerApp import models
from dockerManagerApp.model.base.rpc_client import rpcClientFunction


def docker_pull_image(request):
    ret = {'status': True, 'error': None, 'data': None}
    node_name = request.POST.get("node_name")
    image_name = request.POST.get("image_name")
    hostaddr = ""
    listValue = models.HostManager.objects.filter().values()
    for i in range(len(listValue)):
        hostname = listValue[i].get('hostname')
        if hostname == node_name:
            hostaddr = listValue[i].get('hostaddr')
            status = listValue[i].get('status')
            if status == '1':
                ret['status'] = False
                ret['error'] = u'镜像下载失败,该节点状态为离线'
                return HttpResponse(json.dumps(ret))
            break

    if hostaddr == "":
        ret['status'] = False
        ret['error'] = u'没有查询到节点ip'
        return HttpResponse(json.dumps(ret))
    else:
        rpclient = rpcClientFunction(hostaddr)
        arg_dict = {'image_name': image_name}

        retu = rpclient.dockerPullImage(arg_dict)
        if retu.get('data') != '0':
            ret['status'] = False
            ret['error'] = u'镜像下载失败'
            return HttpResponse(json.dumps(ret))
        else:
            ret['status'] = True
            return HttpResponse(json.dumps(ret))



def create_local_image(request):
    ''''''
    ret = {'status': True, 'error': None, 'data': None}
    node_name = request.POST.get("node_name")
    image_name = request.POST.get("image_name")
    container_name = request.POST.get("container_name")
    hostaddr = ""
    listValue = models.HostManager.objects.filter().values()
    for i in range(len(listValue)):
        hostname = listValue[i].get('hostname')
        if hostname == node_name:
            hostaddr = listValue[i].get('hostaddr')
            status = listValue[i].get('status')
            if status == '1':
                ret['status'] = False
                ret['error'] = u'该节点状态为离线'
                return HttpResponse(json.dumps(ret))
            break

    if hostaddr == "":
        ret['status'] = False
        ret['error'] = u'没有查询到节点ip'
        return HttpResponse(json.dumps(ret))
    else:
        rpclient = rpcClientFunction(hostaddr)
        arg_dict = {
            'image_name': image_name,
            'container_name': container_name
        }

        retu = rpclient.createLocalImage(arg_dict)
        print(retu)
        if retu.get('data') != '0':
            ret['status'] = False
            ret['error'] = u'创建本地镜像失败'
            return HttpResponse(json.dumps(ret))
        else:
            ret['status'] = True
            return HttpResponse(json.dumps(ret))


def del_image(request):
    ret = {'status': True, 'error': None, 'data': None}
    id = request.POST.get("image_id")
    nodeName = request.POST.get("name")
    node_name = nodeName.split(":")[0]

    hostaddr = ""
    listValue = models.HostManager.objects.filter().values()
    for i in range(len(listValue)):
        hostname = listValue[i].get('hostname')
        if hostname == node_name:
            hostaddr = listValue[i].get('hostaddr')
            status = listValue[i].get('status')
            if status == '1':
                ret['status'] = False
                ret['error'] = u'该节点状态为离线'
                return HttpResponse(json.dumps(ret))
            break

    if hostaddr == "":
        ret['status'] = False
        ret['error'] = u'没有查询到节点ip'
        return HttpResponse(json.dumps(ret))
    else:
        rpclient = rpcClientFunction(hostaddr)
        arg_dict = {'id': id}

        retu = rpclient.deleteImage(arg_dict)
        print(retu)
        if retu.get('data') != '0':
            ret['status'] = False
            ret['error'] = u'删除镜像失败'
            return HttpResponse(json.dumps(ret))
        else:
            ret['status'] = True
            return HttpResponse(json.dumps(ret))


def import_image(request):
    ret = {'status': True, 'error': None, 'data': None}

    file_name = request.POST.get("file_name")
    image_name = request.POST.get("image_name")
    node_name = request.POST.get("node_name")
    image_des = request.POST.get("image_des")
    # print(file_name,image_name,node_name)

    hostaddr = ""
    listValue = models.HostManager.objects.filter().values()
    for i in range(len(listValue)):
        hostname = listValue[i].get('hostname')
        if hostname == node_name:
            hostaddr = listValue[i].get('hostaddr')
            status = listValue[i].get('status')
            if status == '1':
                ret['status'] = False
                ret['error'] = u'导入镜像失败,该节点状态为离线'
                return HttpResponse(json.dumps(ret))
            break

    if hostaddr == "":
        ret['status'] = False
        ret['error'] = u'没有查询到节点ip'
        return HttpResponse(json.dumps(ret))
    else:
        rpclient = rpcClientFunction(hostaddr)

        import socket
        myname = socket.getfqdn(socket.gethostname())
        myaddr = socket.gethostbyname(myname)
        arg_dict = {'url': myaddr, 'image_tar_name': file_name, 'image_name': image_name}

        retu = rpclient.importImages(arg_dict)
        if retu.get('data') != '0':
            ret['status'] = False
            ret['error'] = u'导入镜像失败'
            return HttpResponse(json.dumps(ret))
        else:
            ret['status'] = True
            return HttpResponse(json.dumps(ret))


def get_all_images(request):
    allImagesList = []
    count = 1
    listValue = models.HostManager.objects.filter().values()
    for i in range(len(listValue)):
        hostaddr = listValue[i].get('hostaddr')
        status = listValue[i].get('status')
        if status == "1":
            print('offline')
            continue

        rpcClient = rpcClientFunction(hostaddr)
        arg_dict = {}
        try:
            nodeAllImages = rpcClient.getNodeInfomation(arg_dict)
            jsonValue = nodeAllImages['data']
            jsonValue = json.loads(jsonValue)
            imageListV = jsonValue.get('imagesList')
            nodeInfoV = jsonValue.get('nodeInfo')
            nodeMemTotal = nodeInfoV.get('MemTotal')
            nodeNCPU = nodeInfoV.get('NCPU')
            for j in range(len(imageListV)):
                itemImageInfo = {}
                itemImageInfo['hostname'] = listValue[i].get('hostname')
                itemImageInfo['hostaddr'] = hostaddr
                itemImageInfo['Id'] = str(imageListV[j].get('Id'))[7:19]
                itemImageInfo['RepoTags'] = imageListV[j].get('RepoTags')
                itemImageInfo['Size'] = imageListV[j].get('Size')
                itemImageInfo['count'] = count
                itemImageInfo['nodeMemTotal'] = nodeMemTotal
                itemImageInfo['nodeNCPU'] = nodeNCPU

                count = count + 1
                allImagesList.append(itemImageInfo)
        except:
            print('error for rpc')

    if request.GET.get('action') == "getAllImages":
        ret = {'status': True, 'error': None, 'data': None}
        retu_list = []
        node_name = request.GET.get('node_name')
        print('node_name', node_name)
        for i in range(len(allImagesList)):
            if node_name == allImagesList[i]['hostname']:
                image_name = allImagesList[i]['RepoTags']
                host_addr = allImagesList[i]['hostaddr']
                nodeMemTotal = allImagesList[i]['nodeMemTotal']
                nodeNCPU = allImagesList[i]['nodeNCPU']

                iteminfo = {
                    'image_name': image_name,
                    'host_addr': host_addr,
                    'nodeMemTotal': nodeMemTotal,
                    'nodeNCPU': nodeNCPU
                }

                retu_list.append(iteminfo)
        ret['data'] = retu_list
        print(ret)
        return HttpResponse(json.dumps(ret))

    return render(request, 'imagesmanager.html', {'allImagesList': allImagesList})
